package com.eascs.continueloan.controller;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.detail.entity.OaUnit;
import com.eascs.admin.o2o.detail.service.OaLoanapplyDetailService;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.form.AddLoanapplyForm;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.trans.O2oLoanUserTransFormart;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.continueloan.entity.O2oContinueFormEntity;
import com.eascs.continueloan.service.O2oContinueLoanService;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.service.impl.O2oPayServiceImpl;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;

@RestController
@RequestMapping("/rcloan")
public class O2oContinueRestController extends BaseRestController {
	private static Logger log = LoggerFactory.getLogger(O2oContinueRestController.class);
	@Reference
	ICustomerInfoService iCustomerInfoService;
	@Autowired
	O2oContinueLoanService continueLoanService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private BaseUserUtil userUtils;
	@Reference
	private SysOrgService sysOrgService;
	@Autowired
	private O2oPayServiceImpl o2oPayServiceImpl;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private OaLoanapplyDetailService oaLoanapplyDetailService;
	@Reference
	CustomerService customerService ;
	@Autowired
	O2oLoanUserService o2oLoanUserService;

	@RequestMapping("/o2o")
	public PaginationRestResult findPageO2oData(O2oContinueFormEntity entity) {
		entity.setPageSize(10);
		PageResult<Object[]> pageResult = continueLoanService.findO2oByPage(entity);
		String titles[] = { "贷款单号", "借款人姓名", "借款人证件号", "信贷经理", "经营平台", "贷款类型", "申请状态" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("OTO_LOAN_TYPE"), new SelectDataOption("SQZT") };
		String url = "/rcloan/o2o";
		String userName = entity.getUserName() == null ? "" : entity.getUserName();
		String userIdCard = entity.getUserIdCard() == null ? "" : entity.getUserIdCard();
		String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
		url = UrlUtil.appendUrl(url, "billCode", billCode);
		url = UrlUtil.appendUrl(url, "userName", userName);
		url = UrlUtil.appendUrl(url, "userIdCard", userIdCard);
		url = url + "&o2oIndex=";
		PaginationInfo pagingInfo = new PaginationInfo(pageResult, titles, url);
//		Button button = ButtonHelper.createAjaxButton("终端贷续贷", "/rcloan/reloan?ty=" + StatusContexts.DATA_SOURCE_NEW + "&billCode=");
//		Button buttonFQ = ButtonHelper.createAjaxButton("申请分期贷", "/rcloan/fqloan?ty=" + StatusContexts.DATA_SOURCE_NEW + "&billCode=");
//		Button buttonEA = ButtonHelper.createAjaxButton("申请接力贷", "/rcloan/ealoan?ty=" + StatusContexts.DATA_SOURCE_NEW + "&billCode=");
		Button buttonDF = ButtonHelper.createAjaxButton("申请代偿", "/rcloan/dfloan?ty=" + StatusContexts.DATA_SOURCE_NEW + "&billCode=", "applyDf");
		Button[] titleButtons = new Button[] { /*button, buttonFQ, buttonEA,*/ buttonDF };
		pagingInfo.setMoreButtons(titleButtons);
		pagingInfo.setBuildPagingNavigation(true);
		pagingInfo.setSelectDataOptions(selectDataOptions);
		pagingInfo.setFirstRenderColumnIndex(0);
		pagingInfo.setRendTo("#o2o_result");
		ViewContext.put("vo", entity);
		return PaginationRestResult.buildPaginationRestResult(pagingInfo);
	}

	@RequestMapping("/reloan")
	public BaseRestResult<String> reloan(String ty, String billCode) {
		return BaseRestResult.confirm("确认续贷").andActionAjaxLoad("/rcloan/reloan1?ty=" + ty + "&billCode=" + billCode);
	}

	@RequestMapping("/ealoan")
	public BaseRestResult<String> ealoan(String ty, String billCode) {
		return BaseRestResult.confirm("确认接力贷").andActionAjaxLoad("/rcloan/efloan?ty=" + ty + "&billCode=" + billCode + "&loanType=" + StatusContexts.LOAN_TYPE_EA);
	}

	@RequestMapping("/fqloan")
	public BaseRestResult<String> rqloan(String ty, String billCode) {
		return BaseRestResult.confirm("确认分期贷").andActionAjaxLoad("/rcloan/efloan?ty=" + ty + "&billCode=" + billCode + "&loanType=" + StatusContexts.LOAN_TYPE_FQ);
	}

	@RequestMapping("/dfloan")
	public BaseRestResult<String> dfloan(String ty, String billCode) {
		return BaseRestResult.confirm("确认代偿").andActionAjaxLoad("/rcloan/dfloan1?ty=" + ty + "&billCode=" + billCode + "&loanType=" + StatusContexts.LOAN_TYPE_FQ);
	}

	/**
	 * 申请续贷终端贷--页面跳转
	 * 
	 * @param ty
	 * @param billCode
	 * @return
	 */
	@RequestMapping("/reloan1")
	public BaseRestResult<String> reloan1(String ty, String billCode) {
		String id = o2oLoanapplyService.getUserId(billCode);
		log.info("新系统续贷查询用户id：{}", id);
		if (StringUtil.isEmpty(id)) {
			return BaseRestResult.warn("未查询到客户信息，请稍后重试");
		}
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(id);
		log.info("调用CRM用户接口开始，参数：{}", vo.getCustomer_id());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		log.info("在CRM中查询数据结果：用户信息{},资产信息{},配偶信息{},门店信息{}", customer.getBasicInfo(), customer.getAssetInfo(), customer.getExpansionInfo(), customer.getShopInfoList());
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		if (basicEntity == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}
		
		if(basicEntity.getCustomerSd()==null){
			return BaseRestResult.warn("请完善客户基本信息的门店名称字段");
		}
		
		int i = o2oLoanapplyService.getUserLoanContinueCount(id, "'BK','BP'");// check本人是否不可续贷的单
		int j = o2oLoanapplyService.getUserSpouseCanContinueLoanCount(id, "'BK','BP'");// check本人配偶是否有不可续贷的单
		if (i > 0) {
			return BaseRestResult.warn("该借款人在新系统有未放款/逾期/代偿的单，不能续贷");
		}
		if (j > 0) {
			return BaseRestResult.warn("该借款人的配偶在新系统有未放款/逾期/代偿的单，不能续贷");
		}
		return BaseRestResult.redirect(UrlHelper.build("/loanapply/addloan?customerId=" + id + "&billCode=" + billCode + "&loanType=BK&codeType=" + ty));
	}

	/**
	 * 申请接力贷和分期贷 续贷---页面跳转
	 * 
	 * @param ty
	 * @param billCode
	 * @param loanType
	 * @return
	 */
	@RequestMapping("/efloan")
	public BaseRestResult<String> efloan(String ty, String billCode, String loanType) {
		String id = o2oLoanapplyService.getUserId(billCode);
		if (StringUtil.isEmpty(id)) {
			log.info("===================================新系统============返回ID：{}", id);
			return BaseRestResult.warn("未查询到客户信息，请联系运维人员");
		}
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(id);
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		if (basicEntity == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}
		log.info("分期、接力，参数billCode:{}", billCode + ";loanType:" + loanType);
		int i = o2oLoanapplyService.getUserLoanContinueCount(id, "'" + loanType + "'");// check本人是否不可续贷的单
		int j = o2oLoanapplyService.getUserSpouseCanContinueLoanCount(id, "'" + loanType + "'");// check本人配偶是否有不可续贷的单
		String loanTypename = "";
		if ("FQ".equals(loanType)) {
			loanTypename = "分期";
		} else if ("EA".equals(loanType)) {
			loanTypename = "接力";
		}
		if (i > 0) {
			return BaseRestResult.warn("该借款人在新系统有未放款的" + loanTypename + "单，不能提单。");
		}
		if (j > 0) {
			return BaseRestResult.warn("该借款人的配偶在新系统有未放款的" + loanTypename + "单，不能提单。");
		}
		return BaseRestResult.redirect(UrlHelper.build("/loanapply/continueloan?customerId=" + id + "&billCode=" + billCode + "&loanType=" + loanType + "&continueLoanParenNo=" + billCode + "&titleName=" + loanTypename + "&codeType=" + ty));
	}

	/**
	 * 续贷终端贷 保存
	 * 
	 * @param LoanapplyForm
	 * @return
	 */
	@RequestMapping(value = "/saveContinueloanapply", method = RequestMethod.POST)
	public BaseRestResult<String> addLoanApply(AddLoanapplyForm addloanapplyForm) {
		String id = o2oLoanapplyService.getUserId(addloanapplyForm.getBillCode());
		log.info("新系统续贷查询用户id：{}", id);
		if (StringUtil.isEmpty(id)) {
			return BaseRestResult.warn("未查询到客户信息，请联系运维人员修复");
		}
		
		CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(addloanapplyForm.getCustomerId());
		if (customer == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}
		log.info("在CRM中查询数据结果：用户信息{},配偶信息{}", customer.getCustomerName(),  customer.getSpouse());
		
		/*QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(id);
		log.info("调用CRM用户接口开始，参数：{}", vo.getCustomer_id());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		log.info("在CRM中查询数据结果：用户信息{},资产信息{},配偶信息{},门店信息{}", customer.getBasicInfo(), customer.getAssetInfo(), customer.getExpansionInfo(), customer.getShopInfoList());
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		*/
		int i = o2oLoanapplyService.getUserLoanContinueCount(id, "'BK'");// check本人是否不可续贷的单
		int j = o2oLoanapplyService.getUserSpouseCanContinueLoanCount(id, "'BK'");// check本人配偶是否有不可续贷的单
		if (i > 0) {
			return BaseRestResult.warn("该借款人在新系统有未放款的单，不能续贷");
		}
		if (j > 0) {
			return BaseRestResult.warn("该借款人的配偶在新系统有未放款的单，不能续贷");
		}
		BigDecimal loanAmout = new BigDecimal(1000000.00);
		if (addloanapplyForm.getLoanaMount().compareTo(loanAmout) == 1) {
			return BaseRestResult.warn("申请金额不能超过100万");
		} else if (addloanapplyForm.getLoanaMount().compareTo(new BigDecimal(10000.00)) == -1) {
			return BaseRestResult.warn("申请金额不能小于1万");
		}
		ActOrgEntity actOrgEntity = null;
		if (!StringUtil.isEmpty(addloanapplyForm.getLtd1())) {
			addloanapplyForm.setLtd(addloanapplyForm.getLtd1());
			actOrgEntity = sysOrgService.getOrgByUnitNo(addloanapplyForm.getLtd());
		} else {
			actOrgEntity = sysOrgService.getOrgByUnitNo(addloanapplyForm.getLtd());
		}
		O2oLoanapplyEntity o2oLoanapplyEntity = new O2oLoanapplyEntity();
		o2oLoanapplyEntity.setCreatRo(userUtils.getCreateOr());
		o2oLoanapplyEntity.setCreateDate(new Date());
		o2oLoanapplyEntity.setEndRo(userUtils.getCreateOr());
		o2oLoanapplyEntity.setEndDate(new Date());
		o2oLoanapplyEntity.setCreditstatus(1);
		o2oLoanapplyEntity.setIslock(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setLoanType(addloanapplyForm.getLoanType()); // 插入贷款类型
		
		//o2oLoanapplyEntity.setCustomerType(basicEntity.getCustomerType());
		
		// 填写sd数据
		/*o2oLoanapplyEntity.setCustomerCode(basicEntity.getCustomerSd());
		o2oLoanapplyEntity.setCustomeRname(basicEntity.getCustomerName());
		o2oLoanapplyEntity.setCustomerNo(String.valueOf(basicEntity.getCustomerSdNo()));*/
		String customerSdNoSZ[] = addloanapplyForm.getCustomerSdNo().split(",");
		if(customerSdNoSZ.length>3){
			o2oLoanapplyEntity.setCustomerCode(customerSdNoSZ[2]);
			o2oLoanapplyEntity.setCustomeRname(customerSdNoSZ[1]);
			o2oLoanapplyEntity.setCustomerNo(customerSdNoSZ[0]);
		}
		
		o2oLoanapplyEntity.setLoanId(customer.getCustomerId());
		o2oLoanapplyEntity.setLoanFlg(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setWfType(StatusContexts.O2O_NEW);
		o2oLoanapplyEntity.setBankFlg(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setEndDate(new Date());
		o2oLoanapplyEntity.setLoanrate(new BigDecimal(0.0800));
		o2oLoanapplyEntity.setManagefeerate(new BigDecimal(0.0600));
		o2oLoanapplyEntity.setDepositrate(new BigDecimal(0.0500));
		o2oLoanapplyEntity.setContractFlag(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setBcFlag(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setIsPlaceOnFile(StatusContexts.O2O_NEW);
		o2oLoanapplyEntity.setLoanaMount(addloanapplyForm.getLoanaMount());
		o2oLoanapplyEntity.setLtd(addloanapplyForm.getLtd());
		o2oLoanapplyEntity.setDcFlag(StatusContexts.O2O_NO);// 标记是否代偿
		o2oLoanapplyEntity.setContinueLoanParenNo(addloanapplyForm.getBillCode());
		o2oLoanapplyEntity.setLtdName(actOrgEntity.getOrgName());
		o2oLoanapplyEntity.setLoanTerm(addloanapplyForm.getLoanTerm());
		o2oLoanapplyEntity.setOperatorNo(addloanapplyForm.getOperatorNo());
		o2oLoanapplyEntity.setOperatorName(addloanapplyForm.getOperatorName());
		o2oLoanapplyEntity.setReferrerNo(addloanapplyForm.getReferrerNo());
		o2oLoanapplyEntity.setReferrerName(addloanapplyForm.getReferrerName());
		o2oLoanapplyEntity.setRepayMentway(addloanapplyForm.getRepayMentway());
		o2oLoanapplyEntity.setGuarAnteeWay(addloanapplyForm.getGuarAnteeWay());
		o2oLoanapplyEntity.setCommiceRecommend(addloanapplyForm.getCommiceRecommend());
		o2oLoanapplyEntity.setOperationModel(addloanapplyForm.getOperationModel());
		o2oLoanapplyEntity.setBillCode(buildCode(actOrgEntity.getUnitCode(), addloanapplyForm.getLoanType()));
		o2oLoanapplyEntity.setLtdCode(actOrgEntity.getUnitCode());
		o2oLoanapplyEntity.setIsNewNs("Y");
		/*o2oLoanapplyEntity.setBuybackId(addloanapplyForm.getBuybackId());
		OaUnit oaUnit = oaLoanapplyDetailService.findUnit(addloanapplyForm.getBuybackId().trim());
		if (null != oaUnit)
			o2oLoanapplyEntity.setBuybackCode(oaUnit.getUnitCode());
		o2oLoanapplyEntity.setBuybackName(addloanapplyForm.getBuybackName());*/
		if (!StringUtil.isEmpty(addloanapplyForm.getRemark()))
			o2oLoanapplyEntity.setRemark(addloanapplyForm.getRemark().trim());
		O2oLoanUserEntity o2oLoanUserEntity = O2oLoanUserTransFormart.customerNewToloanUser(new O2oLoanUserEntity(), customer, o2oLoanapplyEntity.getLoanapplyNo());
		if (customer != null && customer.getSpouse()!=null) {
			/*QueryCustomerVO vo2 = new QueryCustomerVO();
			vo2.setCustomer_id(customer.getBasicInfo().getMateId());
			CustomerView customer1 = iCustomerInfoService.geCustomerView(vo2);
			CustomerBasicInfoEntity spouseEntity = customer1.getBasicInfo();*/
			O2oLoanUserEntity o2oLoanUserSpouseEntity = O2oLoanUserTransFormart.customerNewToloanUser(new O2oLoanUserEntity(), customer.getSpouse(), o2oLoanapplyEntity.getLoanapplyNo());
			o2oLoanUserSpouseEntity.setSpouseId(o2oLoanUserEntity.getLoanId());
			o2oLoanapplyService.saveContinueEntitys(o2oLoanapplyEntity, o2oLoanUserEntity, o2oLoanUserSpouseEntity, addloanapplyForm);
		} else {
			o2oLoanapplyService.saveContinueEntity(o2oLoanapplyEntity, o2oLoanUserEntity, addloanapplyForm);
		}
		return BaseRestResult.info("保存成功,请上传附件").andRedirect(UrlHelper.build("/loanapply/findloan?loanapplyNo=" + o2oLoanapplyEntity.getLoanapplyNo()));
	}

	/**
	 * 申请接力贷和分期贷 保存
	 * 
	 * @param LoanapplyForm
	 * @return
	 */
	@RequestMapping(value = "/saveEAloanapply", method = RequestMethod.POST)
	public BaseRestResult<String> addEALoanApply(AddLoanapplyForm addloanapplyForm) {
		String id = o2oLoanapplyService.getUserId(addloanapplyForm.getBillCode());
		if (StringUtil.isEmpty(id)) {
			log.info("===================================新系统============返回ID：{}", id);
			return BaseRestResult.warn("未查询到客户信息，请联系运维人员修复");
		}
		// 获取用户的信息
		CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(id);
//		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(id);//查询借款人扩展信息
		if (customer == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}
		log.info("分期、接力，参数billCode:{}", addloanapplyForm.getBillCode() + ";loanType:" + addloanapplyForm.getLoanType());
		int i = o2oLoanapplyService.getUserLoanContinueCount(id, "'" + addloanapplyForm.getLoanType() + "'");// check本人是否不可续贷的单
		int j = o2oLoanapplyService.getUserSpouseCanContinueLoanCount(id, "'" + addloanapplyForm.getLoanType() + "'");// check本人配偶是否有不可续贷的单
		String loanTypename = "";
		if ("FQ".equals(addloanapplyForm.getLoanType())) {
			loanTypename = "分期";
		} else if ("EA".equals(addloanapplyForm.getLoanType())) {
			loanTypename = "接力";
		}
		if (i > 0) {
			return BaseRestResult.warn("该借款人在新系统有未放款的" + loanTypename + "单，不能提单。");
		}
		if (j > 0) {
			return BaseRestResult.warn("该借款人的配偶在新系统有未放款的" + loanTypename + "单，不能提单。");
		}
		BigDecimal loanAmout = new BigDecimal(1000000.00);
		if (addloanapplyForm.getLoanaMount().compareTo(loanAmout) == 1) {
			return BaseRestResult.warn("申请金额不能超过100万");
		} else if (addloanapplyForm.getLoanaMount().compareTo(new BigDecimal(10000.00)) == -1) {
			return BaseRestResult.warn("申请金额不能小于1万");
		}
		ActOrgEntity actOrgEntity = sysOrgService.getOrgByUnitNo(addloanapplyForm.getLtd());
		O2oLoanapplyEntity o2oLoanapplyEntity = new O2oLoanapplyEntity();
		o2oLoanapplyEntity.setCreatRo(userUtils.getCreateOr());
		o2oLoanapplyEntity.setCreateDate(new Date());
		o2oLoanapplyEntity.setEndRo(userUtils.getCreateOr());
		o2oLoanapplyEntity.setEndDate(new Date());
		o2oLoanapplyEntity.setIslock(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setLoanType(addloanapplyForm.getLoanType()); // 插入贷款类型
//		o2oLoanapplyEntity.setCustomerType(customerBasicInfo.getCustomerType());
//		o2oLoanapplyEntity.setCustomerCode(customerBasicInfo.getCustomerSd());
//		o2oLoanapplyEntity.setCustomeRname(customerBasicInfo.getCustomerName());
//		o2oLoanapplyEntity.setCustomerNo(String.valueOf(customerBasicInfo.getCustomerSdNo()));
		o2oLoanapplyEntity.setLoanId(customer.getCustomerId());
		o2oLoanapplyEntity.setLoanFlg(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setWfType(StatusContexts.O2O_NEW);
		o2oLoanapplyEntity.setBankFlg(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setEndDate(new Date());
		o2oLoanapplyEntity.setDcFlag(StatusContexts.O2O_NO);// 标记是否代偿
		o2oLoanapplyEntity.setContractFlag(StatusContexts.O2O_NO);
		if (StatusContexts.LOAN_TYPE_FQ.equals(addloanapplyForm.getLoanType())) {
			o2oLoanapplyEntity.setLoanrate(new BigDecimal(0.08));
			o2oLoanapplyEntity.setManagefeerate(new BigDecimal(0.07));
			o2oLoanapplyEntity.setDepositrate(new BigDecimal(0));
		} else if (StatusContexts.LOAN_TYPE_EA.equals(addloanapplyForm.getLoanType())) {
			o2oLoanapplyEntity.setLoanrate(new BigDecimal(0.18));
			o2oLoanapplyEntity.setManagefeerate(new BigDecimal(0.12));
			o2oLoanapplyEntity.setDepositrate(new BigDecimal(0));
		}
		
		o2oLoanapplyEntity.setContractFlag(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setBcFlag(StatusContexts.O2O_NO);
		o2oLoanapplyEntity.setIsPlaceOnFile(StatusContexts.O2O_NEW);
		o2oLoanapplyEntity.setLoanaMount(addloanapplyForm.getLoanaMount());
		o2oLoanapplyEntity.setLtd(addloanapplyForm.getLtd());
		o2oLoanapplyEntity.setContinueLoanParenNo(addloanapplyForm.getBillCode());
		o2oLoanapplyEntity.setLtdName(actOrgEntity.getOrgName());
		o2oLoanapplyEntity.setLoanTerm(addloanapplyForm.getLoanTerm());
		o2oLoanapplyEntity.setOperatorNo(addloanapplyForm.getOperatorNo());
		o2oLoanapplyEntity.setOperatorName(addloanapplyForm.getOperatorName());
		o2oLoanapplyEntity.setReferrerNo(addloanapplyForm.getReferrerNo());
		o2oLoanapplyEntity.setReferrerName(addloanapplyForm.getReferrerName());
		o2oLoanapplyEntity.setRepayMentway(addloanapplyForm.getRepayMentway());
		o2oLoanapplyEntity.setGuarAnteeWay(addloanapplyForm.getGuarAnteeWay());
		o2oLoanapplyEntity.setBillCode(buildCode(actOrgEntity.getUnitCode(), addloanapplyForm.getLoanType()));
		o2oLoanapplyEntity.setLtdCode(actOrgEntity.getUnitCode());
		o2oLoanapplyEntity.setBuybackId(addloanapplyForm.getBuybackId());
		o2oLoanapplyEntity.setIsNewNs("Y");
		OaUnit oaUnit = oaLoanapplyDetailService.findUnit(addloanapplyForm.getBuybackId().trim());
		if (null != oaUnit)
			o2oLoanapplyEntity.setBuybackCode(oaUnit.getUnitCode());
		o2oLoanapplyEntity.setBuybackName(addloanapplyForm.getBuybackName());
		if (!StringUtil.isEmpty(addloanapplyForm.getRemark()))
			o2oLoanapplyEntity.setRemark(addloanapplyForm.getRemark().trim());
		O2oLoanUserEntity o2oLoanUserEntity = O2oLoanUserTransFormart.customerToloanUser(new O2oLoanUserEntity(), customer, o2oLoanapplyEntity.getLoanapplyNo());
		if (customer != null && customer.getMateId() != null) {
			// 获取用户的信息
			CustomerEntity spouseEntity = customerService.queryCustomerEntityByCustomerId(customer.getMateId());
			O2oLoanUserEntity o2oLoanUserSpouseEntity = O2oLoanUserTransFormart.customerToloanUser(new O2oLoanUserEntity(), spouseEntity, o2oLoanapplyEntity.getLoanapplyNo());
			o2oLoanUserSpouseEntity.setSpouseId(o2oLoanUserEntity.getLoanId());
			o2oLoanapplyService.saveContinueEntitys(o2oLoanapplyEntity, o2oLoanUserEntity, o2oLoanUserSpouseEntity, addloanapplyForm);
		} else {
			o2oLoanapplyService.saveContinueEntity(o2oLoanapplyEntity, o2oLoanUserEntity, addloanapplyForm);
		}
		return BaseRestResult.info("保存成功,请上传附件").andRedirect(UrlHelper.build("/loanapply/findloan?loanapplyNo=" + o2oLoanapplyEntity.getLoanapplyNo()));
	}

	/**
	 * 申请垫付
	 * 
	 * @param ty
	 * @param billCode
	 * @param loanType
	 * @return
	 */
	@RequestMapping("/dfloan1")
	public BaseRestResult<String> dfloan(String ty, String billCode, String loanType) { // loanType 用于是否启动流程
		String id = o2oLoanapplyService.getUserId(billCode);
		if (StringUtil.isEmpty(id)) {
			log.info("===================================新系统============返回ID：{}", id);
			return BaseRestResult.warn("未查询到客户信息，请联系运维人员修复");
		}
		// 加一个是否有垫付流程在运行中的判断
		O2oPayEntity checko2oPayEntity = new O2oPayEntity();
		checko2oPayEntity.setLoanapplyBillcode(billCode);
		checko2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_RUN);
		checko2oPayEntity.setPayType(StatusContexts.PAY_TYPE_DF);
		checko2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		// boolean ishaspay = o2oPayServiceImpl.isHavePayFlow(checko2oPayEntity);
		boolean ishasRUNpay = o2oPayServiceImpl.isHaveRUNPayFlow(checko2oPayEntity);
		if (ishasRUNpay) {
			return BaseRestResult.warn("已经有一个付费流程在流程中，请勿重复启动");
		}
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(id);
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		if (basicEntity == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}
		User user = UserHolder.getUser();
		O2oLoanapplyEntity loanEntity = null;
		loanEntity = o2oLoanapplyService.fingByBillCode(billCode);
		loanEntity.setRepaymentSource(StatusContexts.DATA_SOURCE_NEW);
		loanEntity.setOperatorNo(user.getNo());
		loanEntity.setOperatorName(user.getCname());
		try {
			int i = o2oPayServiceImpl.insertPayByEntity(loanEntity, StatusContexts.PAY_TYPE_DF,basicEntity);
			if(StringUtil.isNotBlank(loanType)){
				if (i > 0) {
					log.info("垫付插入付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
					com.eascs.workflow.common.vo.ModelResult<Boolean> model = o2oPayServiceImpl.startPayFlow(loanEntity, basicEntity.getCustomerName());
					if (model.isSuccess()) {
						log.info("垫付启动付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
						O2oPayEntity o2oPayEntity = o2oPayServiceImpl.findEntityByLoanapplyId(loanEntity.getLoanapplyNo());
						if (null != o2oPayEntity) {
							o2oPayEntity.setSubmitTime(new Date());
							o2oPayEntity.setSubmitUser(loanEntity.getOperatorNo());
							o2oPayEntity.setBillStatus(StatusContexts.O2O_BANK_RUN);
							o2oPayEntity.setLastUpdateTime(new Date());
							o2oPayServiceImpl.updateEntityById(o2oPayEntity);
							log.info("垫付启动付款流程数据成功，贷款单号为：{},更新付款数据成功", loanEntity.getLoanapplyNo());
							return BaseRestResult.info("垫付流程启动成功");
						}
					} else {
						log.error("垫付启动付款流程数据失败，贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), model.getErrMsg());
						return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + model.getErrMsg());
					}
				}
			}else{
				if (i > 0) {
					log.info("垫付插入付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
					return BaseRestResult.info("垫付数据保存成功");
				}else{
					return BaseRestResult.info("垫付数据保存失败");
				}
			}
		} catch (Exception e) {
			log.error("error垫付插入启动付款流程数据失败,贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), e.getMessage());
			return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + e.getMessage());
		}
		return BaseRestResult.warn("垫付流程启动成功");

	}
	
	
	/**
	 * 申请垫付
	 * 
	 * @param ty
	 * @param billCode
	 * @param loanType
	 * @return
	 */
	public BaseRestResult<String> dfloanFx(String ty, String billCode,String payFkType, String loanType,String payid) { // loanType 用于是否启动流程
		String id = o2oLoanapplyService.getUserId(billCode);
		int i = 0;
		if (StringUtil.isEmpty(id)) {
			log.info("===================================新系统============返回ID：{}", id);
			return BaseRestResult.warn("未查询到客户信息，请联系运维人员修复");
		}
		// 加一个是否有垫付流程在运行中的判断
		O2oPayEntity checko2oPayEntity = new O2oPayEntity();
		checko2oPayEntity.setLoanapplyBillcode(billCode);
		checko2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_RUN);
		checko2oPayEntity.setPayType(StatusContexts.PAY_TYPE_DF);
		checko2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		// boolean ishaspay = o2oPayServiceImpl.isHavePayFlow(checko2oPayEntity);
		boolean ishasRUNpay = o2oPayServiceImpl.isHaveRUNPayFlow(checko2oPayEntity);
		if (ishasRUNpay) {
			return BaseRestResult.warn("已经有一个付费流程在流程中，请勿重复启动");
		}
		//QueryCustomerVO vo = new QueryCustomerVO();
		//vo.setCustomer_id(id);
		//CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		//CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		/*if (basicEntity == null) {
			return BaseRestResult.warn("客户系统返回数据为空，请联系运维人员");
		}*/
		
		User user = UserHolder.getUser();
		O2oLoanapplyEntity loanEntity = null;
		loanEntity = o2oLoanapplyService.fingByBillCode(billCode);
		loanEntity.setRepaymentSource(StatusContexts.DATA_SOURCE_NEW);
		loanEntity.setOperatorNo(user.getNo());
		loanEntity.setOperatorName(user.getCname());
		O2oLoanUserEntity loaner =  o2oLoanUserService.findById(loanEntity.getLoanId(), loanEntity.getLoanapplyNo());
		try {

			if(payid==null){
				//i = o2oPayServiceImpl.insertPayByEntityFx(loanEntity, StatusContexts.PAY_TYPE_DF, payFkType, basicEntity);
				i = o2oPayServiceImpl.insertPayByEntityFx(loanEntity, StatusContexts.PAY_TYPE_DF, payFkType, null);
			}else {
				O2oPayEntity o2oPayEntity = o2oPayServiceImpl.findEntityByLoanapplyId(loanEntity.getLoanapplyNo());
				if (null != o2oPayEntity) {
					o2oPayEntity.setLastUpdateTime(new Date());
					o2oPayEntity.setLastUpdateUser(UserHolder.getUser().getNo());
					o2oPayEntity.setPayFkType(payFkType);
					o2oPayServiceImpl.updateEntityById(o2oPayEntity);
					i = o2oPayServiceImpl.updatePayByEntityFx(loanEntity, StatusContexts.PAY_TYPE_DF, payFkType, null);
				}
			}
			
			if(StringUtil.isNotBlank(loanType)){
				if (i > 0) {
					log.info("垫付插入付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
					com.eascs.workflow.common.vo.ModelResult<Boolean> model = o2oPayServiceImpl.startPayFlowFx(loanEntity, loaner.getUserFullName());
					if (model.isSuccess()) {
						log.info("垫付启动付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
						O2oPayEntity o2oPayEntity = o2oPayServiceImpl.findEntityByLoanapplyId(loanEntity.getLoanapplyNo());
						if (null != o2oPayEntity) {
							o2oPayEntity.setSubmitTime(new Date());
							o2oPayEntity.setSubmitUser(loanEntity.getOperatorNo());
							o2oPayEntity.setBillStatus(StatusContexts.O2O_BANK_RUN);
							o2oPayEntity.setLastUpdateTime(new Date());
							o2oPayEntity.setLastUpdateUser(UserHolder.getUser().getNo());
							o2oPayServiceImpl.updateEntityById(o2oPayEntity);
							log.info("垫付启动付款流程数据成功，贷款单号为：{},更新付款数据成功", loanEntity.getLoanapplyNo());
							return BaseRestResult.info("垫付流程启动成功");
						}
					} else {
						log.error("垫付启动付款流程数据失败，贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), model.getErrMsg());
						return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + model.getErrMsg());
					}
				}
			}else{
				if (i > 0) {
					log.info("垫付插入付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
					return BaseRestResult.info("垫付数据保存成功");
				}else{
					return BaseRestResult.info("垫付数据保存失败");
				}
			}
		} catch (Exception e) {
			log.error("error垫付插入启动付款流程数据失败,贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), e.getMessage());
			return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + e.getMessage());
		}
		return BaseRestResult.warn("垫付流程启动成功");

	}
	

	/**
	 * 生成贷款编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code, String type) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + type + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, StatusContexts.O2O_SEQUENCE_LENGTH, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}

}
